from django.shortcuts import render
from django.views.decorators.http import require_POST, require_GET
from django.http import HttpRequest, HttpResponse
import simplejson
from reg.models import User
import bcrypt
from django.contrib.sessions.backends.db import SessionStore

EXPIRE_TIME = 60 * 60

@require_POST
def login(request: HttpRequest):
    data = simplejson.loads(request.body)
    username = data.get("username", 0)
    password = data.get("password", 0)
    remember = data.get("remember", 0)
    if username and password:
        obj = User.objects.filter(username=username).first()
        if obj:
            if bcrypt.checkpw(password.encode(), obj.password.encode()):
                if remember:
                    session: SessionStore = request.session
                    session.set_expiry(EXPIRE_TIME)
                    session["username"] = obj.username
                    session["role"] = obj.role

                return HttpResponse(status=200)
            else:
                return HttpResponse(status=400)
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=400)

@require_GET
def quit(request: HttpRequest):
    session: SessionStore = request.session
    session.flush()
    print("quit ok")
    return HttpResponse(status=200)